<script setup lang="ts">
import {onMounted, onUnmounted, ref} from 'vue';

const visible = ref(false);

const handleOk = () => {
  visible.value = false;
  window.location.reload();
};

const handleCancel = () => {
  console.log('点击了取消');
  visible.value = false;
};

interface Props {
  // 轮训时间，分钟
  checkUpdatesInterval?: number;
  // 检查更新的地址
  checkUpdateUrl?: string;
}

defineOptions({name: 'CheckUpdates'});

const props = withDefaults(defineProps<Props>(), {
  checkUpdatesInterval: 1,
  checkUpdateUrl: import.meta.env.BASE_URL || '/',
});

const lastVersionTag = ref('');
let isCheckingUpdates = false;
const timer = ref<ReturnType<typeof setInterval>>();
async function getVersionTag() {
  try {
    if (
        location.hostname === 'localhost' ||
        location.hostname === '127.0.0.1'
    ) {
      return null;
    }
    const response = await fetch(props.checkUpdateUrl, {
      cache: 'no-cache',
      method: 'HEAD',
    });

    return (
        response.headers.get('etag') || response.headers.get('last-modified')
    );
  } catch {
    console.error('Failed to fetch version tag');
    return null;
  }
}

async function checkForUpdates() {
  const versionTag = await getVersionTag();

  if (!versionTag) {
    return;
  }

  // 首次运行时不提示更新
  if (!lastVersionTag.value) {
    lastVersionTag.value = versionTag;
    return;
  }

  if (lastVersionTag.value !== versionTag && versionTag) {
    clearInterval(timer.value);
    visible.value = true;
  }
}

function start() {
  if (props.checkUpdatesInterval <= 0) {
    return;
  }

  // 每 checkUpdatesInterval(默认值为1) 分钟检查一次
  timer.value = setInterval(
      checkForUpdates,
      props.checkUpdatesInterval * 60 * 1000,
  );
}

function handleVisibilitychange() {
  if (document.hidden) {
    stop();
    return;
  }
  if (!isCheckingUpdates) {
    isCheckingUpdates = true;
    checkForUpdates().finally(() => {
      isCheckingUpdates = false;
      start();
    });
  }
}

function stop() {
  clearInterval(timer.value);
}

onMounted(() => {
  start();
  document.addEventListener('visibilitychange', handleVisibilitychange);
});

onUnmounted(() => {
  stop();
  document.removeEventListener('visibilitychange', handleVisibilitychange);
});
</script>
<template>
  <a-modal v-model:visible="visible" title="新版本可用" @ok="handleOk" @cancel="handleCancel" ok-text="刷新"
           cancel-text="取消">
    <p>点击刷新以获取最新版本。</p>
  </a-modal>
</template>
